<template>
  <div>
    <!-- Tab 切换 -->
    <div class="tabs-container">
      <u-tabs :list="voucherList" @click="clicktabs" lineHeight="5rpx" lineWidth="100rpx"></u-tabs>
    </div>

    <!-- 基本信息模块 -->
    <div class="content-container">
      <div class="section-title">
        <image src="https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/10/10/风车_20251010084002A010.png" class="icon" />
        <div class="title-text">基础信息</div>
        <button class="delete-btn" @click="delVoucher">删除</button>
      </div>

      <!-- 活动券信息 -->
      <div class="input-item">
        <label>活动券:</label>
        <input v-model="voucherForm.name" class="input_class" placeholder="请填写活动名称" />
      </div>

      <div class="input-item">
        <label>活动券数量:</label>
        <input v-model="voucherForm.number" class="input_class" placeholder="请输入活动券数量" />
      </div>

      <div class="input-item">
        <label>限购:</label>
        <input v-model="voucherForm.purchaseLimit" class="input_class" placeholder="请输入限购数量" />
      </div>

      <!-- 上传图标 -->
      <div class="input-item">
        <label>活动券图标:</label>
        <u-upload
          :fileList="voucherForm.fileList"
          @afterRead="afterRead"
          :height="200"
          :width="200"
          @delete="deletePic"
          :name="voucherForm.id"
          :maxCount="10"
          :previewFullImage="true"
        >
          <div class="upload-container">
            <image :src="imgurl + voucherForm.icon" class="icon-image" />
          </div>
        </u-upload>
      </div>
    </div>

    <!-- 详细信息模块 -->
    <div class="content-container">
      <div class="section-title">
        <image src="https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/10/10/风车_20251010084002A010.png" class="icon" />
        <div class="title-text">详细信息</div>
      </div>

      <!-- 上传活动详情图 -->
      <div class="input-item">
        <label>活动详情图片:</label>
        <u-upload
          :fileList="voucherForm.detailFileList"
          @afterRead="afterReadDetail"
          :height="200"
          :width="200"
          @delete="deleteDetailPic"
          :name="voucherForm.id"
          :maxCount="10"
          :previewFullImage="true"
        >
          <div class="upload-container">
            <image :src="voucherForm.graphicInfo" class="icon-image" />
          </div>
        </u-upload>
      </div>

      <div class="input-item">
        <label>价格:</label>
        <input v-model="voucherForm.price" class="input_class" placeholder="请输入" />
      </div>

      <u-cell size="large" title="积分返还:" :value="typeValue" @click="getTypelx" isLink></u-cell>

      <div v-if="voucherForm.isIntegral == 0" class="input-item">
        <label>返还积分:</label>
        <input v-model="voucherForm.integralGive" class="input_class" placeholder="请输入" />
      </div>

      <div class="input-item">
        <label>物业积分抵扣比例:</label>
        <input v-model="voucherForm.integralComunityDiscount" class="input_class" placeholder="最大抵扣：如0.1，代表10%" />
      </div>

      <div class="input-item">
        <label>物业积分抵扣后价格:</label>
        <input v-model="voucherForm.integralComunityDiscountPrice" disabled class="input_class" placeholder="自动计算（价格-抵扣比例*价格）" />
      </div>

      <!-- 关联商品 -->
      <u-cell-group>
        <div class="item-container" @click="showRight = true">
          <div>点击关联商品</div>
          <image src="../../static/z/jia.png" class="icon" />
        </div>
      </u-cell-group>

      <!-- 商品选择弹窗 -->
      <u-popup :show="showRight" mode="right" @close="close" @open="open" :closeOnClickOverlay="false">
        <div class="popup-content">
          <div class="searchButton">
            <input v-model="keywords" class="input_class1" placeholder="请输入商品名称，关键字，商品ID" />
            <button class="search-btn" @click="searchProduct">搜索</button>
          </div>

          <scroll-view class="scroll-view" scroll-y="true">
            <div v-for="(item, index) in spData" @click="selectSp(item)" :class="item.isSelecd ? 'isSelecd' : ''" :key="index" class="product-item">
              <div class="product-info">
                <image :src="imgurl + item.image" class="product-image" />
                <div>
                  <div class="product-name">{{ item.storeName }}</div>
                  <div class="product-price">￥{{ item.price }}</div>
                </div>
              </div>
            </div>
          </scroll-view>

          <div class="confirm-button-container">
            <button class="confirm-button" @click="confirmSelection">确认</button>
          </div>
        </div>
      </u-popup>

      <!-- 已选择商品展示 -->
      <div v-if="okSpForm.length > 0" class="selected-products">
        <div v-for="(item, index) in okSpForm" :key="index" class="selected-product-item">
          <div>
            <div class="product-name">{{ item.name }}</div>
            <div class="product-price">￥{{ item.price }}</div>
          </div>
          <input v-model="item.unmber" type="number" min="0" class="quantity-input" />
        </div>
      </div>
    </div>

    <!-- 日期范围选择弹窗 -->
    <u-calendar :show="show" :mode="mode" rowHeight="100" @confirm="confirm"></u-calendar>

    <!-- 保存按钮 -->
    <u-button type="primary" @click="addOwner">保存</u-button>

    <!-- 新增消费券按钮 -->
    <div class="add-voucher-btn">
      <button @click="addVoucher">新增</button>
    </div>
  </div>
</template>

<script>
// Vue 组件的脚本部分
import { categorylist, addOrUpdateReId, merlist, activityById, productlist, addOrUpdateGather, delProduct } from '../../utils/request_sh.js';
import { IMG_URL } from '../../config/index.js';
export default {
  data() {
    return {
      imgurl: IMG_URL,
      voucherForm: {},
      showRight: false,
      typeValue: '',
      showType: false,
      columns: [],
      voucherList: [],
      spData: [],
      okSpForm: [],
      keywords: '',
      id: ''
    };
  },
  onLoad(option) {
    this.id = option.id;
    this.getDataSp().then(() => {
      this.getSpInfo(option.id);
    });
  },
  methods: {
    // 计算抵扣后的价格
    calculateDiscountedPrice() {
      if (this.voucherForm.price && this.voucherForm.integralComunityDiscount) {
        this.voucherForm.integralComunityDiscountPrice = this.voucherForm.price * (1 - this.voucherForm.integralComunityDiscount);
      } else {
        this.voucherForm.integralComunityDiscountPrice = 0;
      }
    },

    // 商品选择
    selectSp(item) {
      const spDataIndex = this.spData.findIndex((spItem) => spItem.id === item.id);
      if (spDataIndex !== -1) {
        const selected = !this.spData[spDataIndex].isSelecd;
        if (selected) {
          this.spData[spDataIndex].isSelecd = true;
          if (!this.spData[spDataIndex].unmber) {
            this.spData[spDataIndex].unmber = 1;
          }
          this.okSpForm.push({
            ebStoreProductId: item.id,
            name: item.storeName,
            unmber: this.spData[spDataIndex].unmber,
            price: item.price,
            inventory: item.stock
          });
        } else {
          this.spData[spDataIndex].isSelecd = false;
          this.okSpForm = this.okSpForm.filter((spForm) => spForm.ebStoreProductId !== item.id);
        }
      }
    },

    // 获取商品信息
    getDataSp() {
      return new Promise((resolve) => {
        const userInfo = uni.getStorageSync('userInfo');
        const merId = userInfo ? userInfo.merId : '';
        const params = {
          ebMerId: merId,
          userRightComand: 'shanghuAdmin',
          storeType: 3,
          keywords: this.keywords
        };
        this.spData = [];
        productlist(params).then((res) => {
          res.rows.forEach((item) => {
            item.isSelecd = false;
            this.spData.push(item);
          });
          resolve();
        });
      });
    },
    // 获取活动信息
    getSpInfo(id) {
      activityById(id).then((res) => {
        this.voucherList = res.data.ebMerActivityTicketList;
        this.clicktabs(this.voucherList[0]);
        this.initSelectedProducts();
      });
    },
    // 确认选择商品
    confirmSelection() {
      this.okSpForm = [];
      this.spData.forEach((item) => {
        if (item.isSelecd) {
          this.okSpForm.push({
            ebStoreProductId: item.id,
            name: item.storeName,
            unmber: item.unmber || 1,
            price: item.price,
            inventory: item.stock
          });
        }
      });
      this.showRight = false;
    }
  }
};
</script>

<style lang="scss">
/* 优化样式 */
.tabs-container {
  width: 100%;
  height: 35px;
  background-color: #fff;
  border-bottom: 1px solid #ededed;
}

.content-container {
  background-color: #f0f3fb;
  padding: 10px;
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.icon {
  width: 30px;
  height: 30px;
  margin-right: 15px;
}

.title-text {
  font-family: 'PingFang_Bold';
  height: 30px;
  line-height: 30px;
}

.delete-btn {
  margin-left: auto;
  background-color: red;
  border-radius: 50%;
  color: #fff;
  font-size: 12px;
  height: 105rpx;
  width: 105rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.input-item {
  display: flex;
  align-items: center;
  margin-top: 15px;
}

.input_class {
  background-color: #f0f3fb;
  border-radius: 5px;
  width: calc(100% - 90px);
  padding: 12px;
  margin-left: 10px;
  font-size: 13px;
}

.upload-container {
  border: 1px dashed #000;
  border-radius: 3px;
  width: 200rpx;
  height: 200rpx;
  line-height: 200rpx;
  text-align: center;
}

.icon-image {
  width: 90px;
  height: 90px;
}

.scroll-view {
  height: 82vh;
}

.selected-products {
  margin-top: 15px;
}

.selected-product-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  margin-bottom: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.quantity-input {
  width: 60px;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-right: 10px;
}

.add-voucher-btn {
  position: fixed;
  bottom: 650rpx;
  right: 20px;
  z-index: 1000;
  background-color: #007aff;
  border-radius: 50%;
  color: wheat;
  font-size: 12px;
  height: 105rpx;
  width: 105rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
